package user

import properties.PET;

class AuthController {
	
	static allowedMethods = [doIt: "POST"]
	
	def beforeInterceptor = [action:this.&isAuthorized,  except:["login", "doIt", "logout"]]
	
    def userService
    
    def login = {
		if (PET.count() == 0 || Tutor.count() == 0) {
			redirect(controller: "install")
		}
	}
	
	def logout = {
		session.invalidate()
		redirect(controller: "auth", action: "login")
	}

	
    def isAuthorized = {
		if (session.user == null) {
			redirect(controller: "auth", action: "login")
			return false
		}
		return true
	}
	
	def doIt = {
		def user = userService.authenticate(params.username, params.password)

		if (user != null) {
			session.user = user
			redirect(controller: "index")
		} else {
			flash.message = "Login e/ou senha inválidos!"
			redirect(controller: "auth", action: "login")
		}
	}
	
	def hasPermission = {
		return session.user.isAdmin || session.user.id == it
	}
	
}
